package com.pokermind.dse.util;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 精简版Schema修复工具
 * 只添加poker_hands表真正需要的整体状态字段
 * 行动管理字段通过poker_hand_actions表处理
 */
@Component
public class MinimalSchemaFixer {
    
    private final JdbcTemplate jdbcTemplate;
    
    public MinimalSchemaFixer(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    /**
     * 执行精简Schema修复 - 只添加整体状态必需字段
     */
    public void fixMinimalSchema() {
        System.out.println("🔧 开始执行精简Schema修复（只添加整体状态字段）...");
        
        // 只包含手牌整体状态的必需字段
        List<AlterCommand> commands = Arrays.asList(
            // 1. 牌局配置（业务逻辑需要）
            new AlterCommand("ante", "DECIMAL(10,2) DEFAULT 0", "前注金额"),
            
            // 2. 最终结果字段（无法通过actions表计算）
            new AlterCommand("final_pot", "DECIMAL(10,2) DEFAULT 0", "最终底池金额"),
            new AlterCommand("rake_amount", "DECIMAL(10,2) DEFAULT 0", "抽水金额"),
            
            // 3. 扩展数据字段（整体信息快照）
            new AlterCommand("players_info", "JSON", "玩家信息JSON数据"),
            new AlterCommand("final_results", "JSON", "最终结果JSON数据"),
            
            // 4. 时间统计
            new AlterCommand("duration_seconds", "INT DEFAULT 0", "手牌持续时间(秒)")
        );
        
        System.out.println("📋 精简方案说明:");
        System.out.println("  ✅ 保留：基础配置、最终结果、扩展数据");
        System.out.println("  ❌ 移除：实时行动管理字段（通过poker_hand_actions表处理）");
        System.out.println("  📊 减少字段数：从34个减少到" + (getCurrentFieldCount() + commands.size()) + "个");
        
        int successCount = 0;
        int skipCount = 0;
        int errorCount = 0;
        
        for (AlterCommand command : commands) {
            try {
                if (columnExists(command.columnName)) {
                    System.out.println("  ✓ 字段 " + command.columnName + " 已存在，跳过");
                    skipCount++;
                } else {
                    executeAlterTable(command);
                    System.out.println("  ✅ 成功添加字段: " + command.columnName);
                    successCount++;
                }
            } catch (Exception e) {
                System.err.println("  ❌ 添加字段 " + command.columnName + " 失败: " + e.getMessage());
                errorCount++;
            }
        }
        
        System.out.println("🎯 精简Schema修复完成!");
        System.out.println("📊 统计: 成功添加 " + successCount + " 个字段，跳过 " + skipCount + " 个字段，失败 " + errorCount + " 个字段");
        
        if (errorCount == 0) {
            System.out.println("✨ 精简版Schema修复完成！");
            System.out.println("⚠️  注意: 需要修改DAO代码以适应精简版字段");
        }
    }
    
    /**
     * 获取当前字段数量
     */
    private int getCurrentFieldCount() {
        try {
            String sql = """
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = 'soulwork' AND TABLE_NAME = 'poker_hands'
                """;
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
            return count != null ? count : 0;
        } catch (Exception e) {
            return 0;
        }
    }
    
    /**
     * 检查字段是否存在
     */
    private boolean columnExists(String columnName) {
        try {
            String sql = """
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = 'soulwork' 
                AND TABLE_NAME = 'poker_hands' 
                AND COLUMN_NAME = ?
                """;
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class, columnName);
            return count != null && count > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 执行ALTER TABLE语句
     */
    private void executeAlterTable(AlterCommand command) {
        String sql = String.format(
            "ALTER TABLE poker_hands ADD COLUMN %s %s COMMENT '%s'", 
            command.columnName, 
            command.dataType, 
            command.comment
        );
        
        System.out.println("  🔨 执行: " + sql);
        jdbcTemplate.execute(sql);
    }
    
    /**
     * 显示需要从DAO代码中移除的字段
     */
    public void showFieldsToRemoveFromDAO() {
        System.out.println("\n🔧 需要从DAO代码中移除的字段（通过poker_hand_actions表处理）:");
        System.out.println("-".repeat(60));
        
        String[] fieldsToRemove = {
            "next_action_seat",     // 通过查询最后action计算
            "active_players",       // 通过业务逻辑计算 
            "to_call",             // 通过最后bet/raise计算
            "min_raise",           // 通过游戏规则计算
            "status",              // 通过completed_at判断
            "total_actions"        // COUNT(*) from actions表
        };
        
        for (String field : fieldsToRemove) {
            System.out.println("  ❌ " + field);
        }
        
        System.out.println("-".repeat(60));
        System.out.println("📝 这些字段的获取方式:");
        System.out.println("  • next_action_seat: 通过calculateNextActionSeat()方法");
        System.out.println("  • active_players: 通过统计非fold玩家");
        System.out.println("  • to_call/min_raise: 通过最后行动计算");
        System.out.println("  • status: completed_at IS NULL ? 'active' : 'completed'");  
        System.out.println("  • total_actions: COUNT查询actions表");
    }
    
    /**
     * ALTER命令内部类
     */
    private static class AlterCommand {
        final String columnName;
        final String dataType;
        final String comment;
        
        AlterCommand(String columnName, String dataType, String comment) {
            this.columnName = columnName;
            this.dataType = dataType;
            this.comment = comment;
        }
    }
}
